<template>
	<view class="login-container">
		<!-- 提示登录的图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<!-- <button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button> -->
		  <!-- <button type="primary" class="btn-login" @click="getUserProfile">一键登录</button> -->
		  <button type="primary" class="btn-login" @click="show">一键登录</button>
		<!-- 登录提示 -->
		<view class="tips-text">登录后尽享更多权益</view>
		
		
		<uni-popup class="popup" ref="popup" type="center" background-color="#fff">
			
			<view class="infoBox">
				<button  class="avatar-wrapper" open-type='chooseAvatar' @chooseavatar='onChooseAvatar'>
					<image class="avatar" :src="imgUrl" mode=""></image>
				</button>
				
				<view class="nickname-wrapper">
					<text class="nickname-label">昵称</text>
					<input type="nickname" class="nickname-input" placeholder="请输入昵称"  @blur="onInputChange" />
				</view>
			
				<view class="btn-wrapper">
					<button type="primary" size='mini'	 @click="getUserProfile">确定</button>
					<!-- <button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button> -->
				</view>
			</view>
			
		</uni-popup>
		
	</view>
</template>

<script>
	import { mapMutations ,mapState } from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				imgUrl:'',
				name:'',
				info:{},
				token:''
			};
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo','updateToken','updateRedirectInfo']),
			// 获取微信用户的基本信息
			getUserInfo(e) {
		       // 判断是否获取用户信息成功
		       if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权！')
		       // 获取用户信息成功， e.detail.userInfo 就是用户的基本信息
		       console.log(e.detail)
		 
		       // 3. 将用户的基本信息存储到 vuex 中
			   this.info = e.detail.userInfo
			   this.info.avatarUrl = this.imgUrl
			   this.info.nickName = this.name
		       this.updateUserInfo(this.info)
			   
			   // 获取登录成功后的 Token 字符串
			     this.getToken(e.detail)
			 
			},
			 getUserProfile() {
			        if(this.imgUrl.length>0&&this.name.length>0){
						uni.getUserProfile({
						  desc: '你的授权信息',
						  success: (res) => {
						    // 将信息存到 vuex 中
							console.log(res)
							this.info = res.userInfo
							this.info.avatarUrl = this.imgUrl
							this.info.nickName = this.name
						    this.updateUserInfo(this.info)
						    this.getToken(res)
						  },
						  fail: (res) => {
						    return uni.$showMsg('您取消了登录授权')
						  }
						})
					}else{
						 uni.$showMsg('请先确定信息')
					}
			},		
			// 调用登录接口，换取永久的 token
			async getToken(info) {
			  // 调用微信登录接口
			  const res = await uni.login().catch(err => err)
			  console.log(res) //code
			//   // 判断是否 uni.login() 调用失败
			  if (res.errMsg !== 'login:ok') return uni.$showError('登录失败！')
			
			  // 准备参数对象
			  const query = {
			    code: res.code,
			    encryptedData: info.encryptedData,
			    iv: info.iv,
			    rawData: info.rawData,
				// rawData: JSON.stringify(this.info),
			    signature: info.signature
			  }
				console.log(query)
			  // 换取 token  
			  // const {data: loginResult} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
			  // console.log(loginResult)
			  // if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')
			  // uni.$showMsg('登录成功')
			  // this.updateToken(loginResult.message.token)
			  this.updateToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo')
			  
			  // uni.request({
			  //     url: 'https://api.weixin.qq.com/cgi-bin/token',
			  //     data: {
			  //         grant_type:'client_credential',
			  //         appid:'wxc5646eece19f5995',
			  //         secret:'83b9c762f73384e9c8b9a4d0d6aa4b9f'
			  //     },
			  //     success: (res) => {
			  //         console.log(res.data);
					//   this.updateToken(res.data.access_token)
			  //     }
			  // });
			  this.navigateBack()
			},
			show(){
				this.$refs.popup.open('center')
			},
			//获取头像
			async onChooseAvatar(e){
				this.imgUrl = e.detail.avatarUrl
				console.log(this.imgUrl)
				uni.showToast({
					title:"头像设置成功",
					duration:1000
				})
			},
			async onInputChange(e){
				console.log(e.detail.value)
				this.name = e.detail.value
			},
			navigateBack() {
			  // redirectInfo 不为 null，并且导航方式为 switchTab
			  if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
			    // 调用小程序提供的 uni.switchTab() API 进行页面的导航
			    uni.switchTab({
			      // 要导航到的页面地址
			      url: this.redirectInfo.from,
			      // 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
			      complete: () => {
			        this.updateRedirectInfo(null)
			      }
			    })
			  }
			}
		},
		
		computed: {
			// 调用 mapState 辅助方法，把 m_user 模块中的数据映射到当前用组件中使用
			...mapState('m_user', ['redirectInfo']),
		},
	}
</script>

<style lang="scss">
.login-container {
  // 登录盒子的样式
  height: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  position: relative;
  overflow: hidden;

  // 绘制登录盒子底部的半椭圆造型
  &::after {
    content: ' ';
    display: block;
    position: absolute;
    width: 100%;
    height: 40px;
    left: 0;
    bottom: 0;
    background-color: white;
    border-radius: 100%;
    transform: translateY(50%);
  }

  // 登录按钮的样式
  .btn-login {
    width: 90%;
    border-radius: 100px;
    margin: 15px 0;
    background-color: #c00000;
  }

  // 按钮下方提示消息的样式
  .tips-text {
    font-size: 12px;
    color: gray;
  }
}

:deep(.uni-popup__wrapper){
	border-radius: 50px;
}


.infoBox{
	width: 500rpx;
	padding: 20px;
}

.avatar-wrapper {
  padding: 0;
  width: 56px !important;
  border-radius: 8px;
  margin-top: 40px;
  margin-bottom: 40px;
}

.avatar {
  display: block;
  width: 56px;
  height: 56px;
}
.nickname-wrapper {
  display: flex;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  border-top: .5px solid rgba(0, 0, 0, 0.1);
  border-bottom: .5px solid rgba(0, 0, 0, 0.1);
  color: black;
}

.nickname-label {
  width: 80px;
}

.nickname-input {
  flex: 1;
}
.btn-wrapper{
	display: flex;
	margin-top: 10px;
}
</style>